//
//  ZHLEEOAuthController.swift
//  ZHBlog_swift
//
//  Created by ZHLEEBlander on 15/10/14.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class ZHLEEOAuthController: UIViewController,UIWebViewDelegate {

    let App_ID = "31375771"
    let App_Secret = "2bc4197a6ebca47571d6a347b80b67e1"
    let REDIRECT_URL = "http://www.baidu.com"
    
    var webView : UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        
        //提供登陆界面
        //用webView加载
        
        let webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        webView.delegate = self
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(App_ID)&response_type=code&redirect_uri=\(REDIRECT_URL)"
        
//        printLog(urlStr)
        
        let url = NSURL(string: urlStr)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        view.addSubview(webView)
        self.webView = webView
        
    }
    
    private func setupNav(){
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "aotuinput")
        
    }
    
    @objc private func aotuinput(){
        
        let script = "document.getElementById('userId').value='18202853137';document.getElementById('passwd').value='qq675682650'"
        
        self.webView?.stringByEvaluatingJavaScriptFromString(script)
        
    }
    
    // MARK: - UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        if urlString!.hasPrefix(REDIRECT_URL){
         
            let codePre = "code="
            
            let range = (urlString! as NSString).rangeOfString(codePre)
            
            if range.location != NSNotFound{
            
                //code里面有值
                //截取
                let code = (urlString! as NSString).substringFromIndex(range.location + range.length)
                
//                printLog(code)
                
                loadAccessToken(code)
                
                return false
            }
        }
        return true
    }
    
    private func loadAccessToken(code:String){
    
        let AFManager = AFHTTPSessionManager()
        //给默认的的序列化器添加一个可以接受的内容类型
        AFManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let postStr = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id" : App_ID,
            "client_secret" : App_Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : REDIRECT_URL
        ]
        // MARK: - 继续
        AFManager.POST(postStr, parameters: params, success: { (datatask, result) -> Void in
            //请求成功
            printLog("请求成功:\(result)")
            if let res = (result as? [String : AnyObject]){
            
                let account = ZHLEEUserAccount(dictionary: res)
                
                self.loadUserInfo(account)
            }
            
        }) { (datatask, error) -> Void in
            //请求失败
            printLog("请求失败:\(error)")
        }
        
    }
    
    private func loadUserInfo(account:ZHLEEUserAccount){
    
        let manager = AFHTTPSessionManager()
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
        
            "access_token": account.access_token!,
            "uid": account.uid!
        ]
        
        manager.GET(urlString, parameters: params, success: { (datatask, result) -> Void in
       
            if let res = (result as? [String : AnyObject]){
            
                account.avatar_large = res["avatar_large"] as? String
                account.name = res["name"] as? String
                
                //保存用户信息
                account.saveAccount()
                
                SVProgressHUD.dismiss()
                
                let window = UIApplication.sharedApplication().delegate?.window!
                
                window?.rootViewController = ZHLEEWelcomeController()
                
            }
            
        }) { (datatask, error) -> Void in
                
        }
        
    }

}
